#!/usr/bin/env python3
"""
API调试脚本
用于测试后端API连接和功能
"""

import requests
import json

# 基础URL
BASE_URL = "http://localhost:8000"

def test_connection():
    """测试基本连接"""
    print("=== 测试基本连接 ===")
    try:
        response = requests.get(f"{BASE_URL}/accounts/test/")
        print(f"状态码: {response.status_code}")
        print(f"响应内容: {response.text}")
        return response.status_code == 200
    except Exception as e:
        print(f"连接失败: {e}")
        return False

def test_image_captcha():
    """测试图片验证码"""
    print("\n=== 测试图片验证码 ===")
    try:
        import uuid
        test_uuid = str(uuid.uuid4())
        response = requests.get(f"{BASE_URL}/accounts/getimagecode/?uuid={test_uuid}")
        print(f"状态码: {response.status_code}")
        print(f"响应类型: {response.headers.get('content-type')}")
        if response.status_code == 200:
            print("✅ 图片验证码接口正常")
            return test_uuid
        else:
            print(f"❌ 图片验证码接口失败: {response.text}")
            return None
    except Exception as e:
        print(f"图片验证码测试失败: {e}")
        return None

def test_sms_login():
    """测试短信登录"""
    print("\n=== 测试短信登录 ===")
    try:
        data = {
            'phone': '19939035516',
            'code': '123456'
        }
        response = requests.post(f"{BASE_URL}/accounts/sms-login/", json=data)
        print(f"状态码: {response.status_code}")
        print(f"响应内容: {response.text}")
        
        if response.status_code == 200:
            result = response.json()
            print("✅ 短信登录成功")
            return result.get('token')
        else:
            print("❌ 短信登录失败")
            return None
    except Exception as e:
        print(f"短信登录测试失败: {e}")
        return None

def test_with_token(token):
    """测试带token的请求"""
    print(f"\n=== 测试带token的请求 ===")
    try:
        headers = {
            'Authorization': f'Bearer {token}'
        }
        response = requests.get(f"{BASE_URL}/accounts/test/", headers=headers)
        print(f"状态码: {response.status_code}")
        print(f"响应内容: {response.text}")
        
        if response.status_code == 200:
            print("✅ 带token的请求成功")
        else:
            print("❌ 带token的请求失败")
    except Exception as e:
        print(f"带token请求测试失败: {e}")

def main():
    """主测试函数"""
    print("开始API调试...\n")
    
    # 测试基本连接
    if not test_connection():
        print("基本连接失败，请检查Django服务是否启动")
        return
    
    # 测试图片验证码
    uuid_value = test_image_captcha()
    
    # 测试短信登录
    token = test_sms_login()
    
    # 测试带token的请求
    if token:
        test_with_token(token)
    
    print("\n=== 调试完成 ===")

if __name__ == "__main__":
    main() 